/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi.pb138.srgsxmldb.servlets;

import cz.muni.fi.pb138.srgsxmldb.fileUtils.FileUtil;
import cz.muni.fi.pb138.srgsxmldb.manager.IXManager;
import cz.muni.fi.pb138.srgsxmldb.manager.XManager;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;

/**
 * this class provides downloading desired xml srgs grammar in JSGF
 * 
 * @author Eldred
 */
public class DownloadJSGF extends HttpServlet{
 
    private static final int BYTES_DOWNLOAD = 1024;
 
    @Override
    public void doGet(HttpServletRequest request, 
    HttpServletResponse response) throws IOException{

        String filename = (String) request.getParameter("file");

        if (filename != null) {

            IXManager manager = new XManager();
            File file = manager.getGrammarFileByFileName(filename);            
            ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
            URL xslIn = classLoader.getResource("xslt/SRGStoJSGF.xsl");
            
            try {
                FileUtil.transform(file.getAbsolutePath(), xslIn.toString(), file.getName()+".txt");
            } catch (TransformerConfigurationException ex) {
                Logger.getLogger(DownloadJSGF.class.getName()).log(Level.SEVERE, null, ex);
            } catch (TransformerException ex) {
                Logger.getLogger(DownloadJSGF.class.getName()).log(Level.SEVERE, null, ex);
            }
            
            File jsgf = new File(file.getName()+".txt");
            
            FileInputStream fileToDownload = new FileInputStream(jsgf);

            response.setContentType("text/plain");
            response.setHeader("Content-Disposition", "attachment;filename="+jsgf.getName()); 

            int read=0;
            byte[] bytes = new byte[BYTES_DOWNLOAD];
            OutputStream os = response.getOutputStream();


                while((read = fileToDownload.read(bytes))!= -1){
                        os.write(bytes, 0, read);
                }

            os.flush();
            os.close();
            //jsgf.delete();
            fileToDownload.close();
            jsgf.delete();
        }
    }
}
